package com.sheepone.distributor;

import com.lmax.disruptor.EventTranslator;
import com.sheepone.distributor.config.WorkerStationConfig;
import com.sheepone.distributor.event.WorkEvent;
import com.sheepone.distributor.listener.StationEventListener;
import com.sheepone.distributor.thread.LoadExecutorHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Miss.杨
 * @description
 * @since 2023-12-07 21:53
 */
public class WorkerStation extends DisruptorHolder<WorkEvent> {
    private final static Logger LOGGER = LoggerFactory.getLogger(WorkerStation.class);
    private final ConcurrentHashMap<String, StationEventListener<?>> listeners = new ConcurrentHashMap<>();

    public WorkerStation(WorkerStationConfig config) {
        super(config.getStation(), WorkEvent::new);
        int size = config.getLineSize();
        if (size < 1) {
            throw new IllegalArgumentException("size must be greater than 0");
        }
        LoadExecutorHolder executorHolder = new LoadExecutorHolder(name, config.getHandlerNum(), config.getKeepAliveTime());
        WorkerStationManager.INSTANCE.registerThreadPool(name, executorHolder);
        this.handler = new WorkerLineHandler(executorHolder);
        this.line = newDisruptor(size);
        this.line.start();
        LOGGER.info("【WorkerStation】 \"{}\" start to work", name);
    }

    public boolean register(String topic, StationEventListener<?> listener) {
        if (listeners.get(topic) != null) {
            return false;
        }
        listeners.put(topic, listener);
        return true;
    }

    public StationEventListener<?> getEventListener(String topic) {
        return listeners.get(topic);
    }


    /**
     * 暴露发布事件的方法
     */
    public void publish(EventTranslator<WorkEvent> translator) {
        line.getRingBuffer().publishEvent(translator);
    }

    @Override
    public void stop() {
        line.halt();
        LOGGER.info("【WorkerStation】 \"{}\" has stopped", name);
    }

    @Override
    public String toString() {
        return "WorkerStation{" +
                "name='" + name + '\'' +
                '}';
    }
}
